package com.dev.module_zqc_sleep.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import com.dev.module_zqc_sleep.R
import com.dev.module_zqc_sleep.databinding.ActivityPlayAudioBinding
import com.dev.module_zqc_sleep.utils.FileUtils
import com.fwlst.lib_base.activity.BaseMvvmActivity
import com.fwlst.lib_base.model.BaseViewModel
import com.fwlst.lib_base.utils.AdUtils
import com.fwlst.lib_base.utils.JtXXPermissions
import com.litao.slider.Utils
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.util.Calendar

@Suppress("DEPRECATION")
class PlayAudioActivity : BaseMvvmActivity<ActivityPlayAudioBinding, BaseViewModel>() {
    private var isPlay = false //播放状态
    private val mediaPlayer: MediaPlayer = MediaPlayer()
    private lateinit var mHandler: Handler

    private val audioPath: String by lazy { intent.getStringExtra(EXTRA_AUDIO_PATH)!! }
    private val layoutTitle: String by lazy { intent.getStringExtra(EXTRA_LAYOUT_TITLE)!! }

    companion object {
        private const val EXTRA_AUDIO_PATH = "audioPath"
        private const val EXTRA_LAYOUT_TITLE = "layoutTitle"

        fun start(context: Context, audioPath: String, title: String) {
            val intent = Intent(context, PlayAudioActivity::class.java).apply {
                putExtra(EXTRA_AUDIO_PATH, audioPath)
                putExtra(EXTRA_LAYOUT_TITLE, title)
            }
            context.startActivity(intent)
        }
    }

    override fun initLayout(): Int = R.layout.activity_play_audio

    override fun initBR(): Int = 0

    override fun initView() {

        AdUtils.loadBannerAd(this, binding.bannerContainer)
        // 返回按钮
        binding.returnTb.setNavigationOnClickListener { finish() }
        binding.customsTbTitle.text = layoutTitle
        // 播放/暂停点击事件
        binding.hpYpjjTiQuPlay.setOnClickListener {
            if (isPlay) {
                // 暂停播放
                if (mediaPlayer.isPlaying) {
                    mediaPlayer.pause()
                }
                // 暂停动画
                binding.hpYpjjTiQuPlayImg.clearAnimation()
                binding.hpYpjjTiQuPlay.setImageResource(R.mipmap.module_first_img7)
                isPlay = !isPlay
            } else {
                // 开始播放
                if (!mediaPlayer.isPlaying) {
                    mediaPlayer.start()
                }
                // 启动定时器
                // setTime();
                // 开始动画
                val animation = AnimationUtils.loadAnimation(mContext, R.anim.music_rotate_anim1)
                val lin = LinearInterpolator() //设置动画匀速运动
                animation.interpolator = lin
                binding.hpYpjjTiQuPlayImg.startAnimation(animation)
                binding.hpYpjjTiQuPlay.setImageResource(R.mipmap.module_first_img12)
                binding.hpYpjjTiQuPlay.layoutParams.height = Utils.dpToPx(45)
                binding.hpYpjjTiQuPlay.layoutParams.width = Utils.dpToPx(45)
                isPlay = !isPlay
            }
        }
        mediaPlayer.setOnCompletionListener { _: MediaPlayer? ->
            // 播放完成，清理工作或播放下一首歌曲
            // 暂停动画
            binding.hpYpjjTiQuPlayImg.clearAnimation()
            binding.hpYpjjTiQuPlay.setImageResource(R.mipmap.module_first_img7)
            isPlay = !isPlay
        }
        // 设置监听器
        binding.hpYpjjTiQuSeekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                // 拖动进度条，改变播放进度
                if (fromUser) {
                    mediaPlayer.seekTo(progress)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })
        // 保存
        binding.hpYpjjTiQuSave.setOnClickListener {
            JtXXPermissions.requestGallery(this) {
                copyFileByUri(audioPath)
            }
        }
        // 选择视频文件
        initMediaPlayer(audioPath)
        mHandler = Handler(Looper.getMainLooper())
        startRepeatedTask()
    }

    private fun startRepeatedTask() {
        mHandler.postDelayed({

            // 执行任务逻辑
            // 更新SeekBar的进度
            binding.hpYpjjTiQuSeekBar.progress = mediaPlayer.currentPosition
            runOnUiThread {
                binding.hpYpjjTiQuTime1.text =
                    FileUtils.formatTime(mediaPlayer.currentPosition / 1000)
            }
            // 继续下一次定时任务
            startRepeatedTask()
        }, 500) // 1秒后执行
    }

    @SuppressLint("SetTextI18n")
    private fun initMediaPlayer(path: String) {
        try {
            // File file=new File(Environment.getExternalStorageDirectory(),"music.mp3");//注意声明处理危险权限：<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE/>"
            // mediaPlayer.setDataSource(file.getPath());
            val file = File(path)
            binding.hpYpjjTiQuName.text = file.name
            binding.hpYpjjTiQuSize.text = "大小： ${FileUtils.getDirOrFileSize(path)}"
            mediaPlayer.setDataSource(path)
            mediaPlayer.prepare()
            // 设置最大值
            binding.hpYpjjTiQuSeekBar.max = mediaPlayer.duration
            // 设置时长
            binding.hpYpjjTiQuTime2.text = FileUtils.formatTime(mediaPlayer.duration / 1000)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // 保存音频到本地
    private fun copyFileByUri(path: String) {
        val mFile = File(path)
        //存入Download文件夹
        val savePath =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath
        val filename = Calendar.getInstance().timeInMillis.toString()
        val saveFile = File(savePath, mFile.name)
        var inStream: FileInputStream? = null
        var outStream: FileOutputStream? = null
        try {
            inStream = FileInputStream(File(path))
            outStream = FileOutputStream(saveFile)
            val inChannel = inStream.channel
            val outChannel = outStream.channel
            inChannel.transferTo(0, inChannel.size(), outChannel)
            // 弹窗提示
//            DownBitmap.succeedDialog(mContext, Environment.DIRECTORY_DOWNLOADS)  //todo.....
            // 把图片保存后声明这个广播事件通知系统相册有新图片到来
            val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
            val newUri = Uri.fromFile(File("$savePath/$filename.mp3"))
            intent.setData(newUri)
            sendBroadcast(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                inStream?.close()
                outStream?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer.stop() // 暂停
        mediaPlayer.reset() // 重置
        mediaPlayer.release() // 注销
        mHandler.removeCallbacksAndMessages(null)
        AdUtils.destroyBannerAd()
    }
}